from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.data_list = []

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout()

        self.list_widget = QListWidget()
        self.layout.addWidget(self.list_widget)

        self.add_button = QPushButton("添加")
        self.layout.addWidget(self.add_button)

        self.delete_button = QPushButton("删除")
        self.layout.addWidget(self.delete_button)

        self.edit_button = QPushButton("编辑")
        self.layout.addWidget(self.edit_button)

        self.search_button = QPushButton("查找")
        self.layout.addWidget(self.search_button)

        self.central_widget.setLayout(self.layout)

        self.add_button.clicked.connect(self.add_item)
        self.delete_button.clicked.connect(self.delete_item)
        self.edit_button.clicked.connect(self.edit_item)
        self.search_button.clicked.connect(self.search_item)

    def add_item(self):
        item_text, ok = QInputDialog.getText(self, "添加数据", "请输入要添加的数据:")
        if ok and item_text:
            self.data_list.append(item_text)
            self.list_widget.addItem(item_text)

    def delete_item(self):
        selected_item = self.list_widget.currentItem()
        if selected_item:
            index = self.list_widget.row(selected_item)
            del self.data_list[index]
            self.list_widget.takeItem(index)

    def edit_item(self):
        selected_item = self.list_widget.currentItem()
        if selected_item:
            item_text, ok = QInputDialog.getText(self, "编辑数据", "请输入新的数据:", text=selected_item.text())
            if ok and item_text:
                index = self.list_widget.row(selected_item)
                self.data_list[index] = item_text
                selected_item.setText(item_text)

    def search_item(self):
        search_text, ok = QInputDialog.getText(self, "查找数据", "请输入要查找的数据:")
        if ok and search_text:
            for i, item in enumerate(self.data_list):
                if search_text in item:
                    self.list_widget.setCurrentRow(i)
                    break
            else:
                QMessageBox.information(self, "查找结果", "未找到匹配的数据")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
